<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 * @property int $id
 * @property int $user_id
 * @property int $relation_user_id
 * @property int $relation_type
 * @property \Carbon\Carbon $create_time
 * @property \Carbon\Carbon $update_time
 * @property int $delete_time
 */
class UserRelation extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user_relation';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'user_id' => 'integer', 'relation_user_id' => 'integer', 'relation_type' => 'integer', 'create_time' => 'datetime', 'update_time' => 'datetime', 'delete_time' => 'integer'];

    public function userName()
    {
        return $this->hasOne(User::class, 'user_id', 'user_id');
    }

    /**
     * 增加一个关系记录.
     * @param $userId
     * @param $relationUserId
     * @param $relationType
     */
    public function addOne($userId, $relationUserId, $relationType): int
    {
        $this->user_id = $userId;
        $this->relation_user_id = $relationUserId;
        $this->relation_type = $relationType;
        $this->save();
        return $this->id;
    }

    /**
     * 删除一个关系.
     * @param $userId
     * @param $relationUserId
     * @param $relationType
     */
    public function deleteOne($userId, $relationUserId, $relationType): bool
    {
        UserRelation::query()->where('user_id', $userId)
            ->where('relation_user_id', $relationUserId)
            ->where('relation_type', $relationType)
            ->delete();
        return true;
    }
}
